<template>
  <view class="container" style="padding-bottom: 100px" v-if="isLoaded">
    <!-- 表单 -->
    <view class="content">
      <li-form>
        <uni-section class="section-mg" title="积分规则" />
        <li-form-item label="销售方式">
          <li-picker
            v-model="form.pointType"
            :range-list="[
              {
                id: 1,
                text: '按金额积分',
              },
              {
                id: 2,
                text: '按商品积分',
              },
            ]"
          />
        </li-form-item>
        <li-form-item :border="false" v-show="form.pointType == 1">
          <view class="inner-input-container" style="padding-left: 80px">
            每消费<li-input
              class="inner-input"
              rule="float"
              v-model="form.spendPerPoint"
            />元获得1积分
          </view>
        </li-form-item>
        <li-form-item label="积分支付" :border="false">
          <view class="inner-input-container">
            每<li-input
              class="inner-input"
              v-model="form.pointPerYuan"
            />积分可抵用1元现金
          </view>
        </li-form-item>
        <li-form-item label="清空积分" :border="false">
          <li-switch v-model="form.resetPoints" />
        </li-form-item>
        <uni-section class="section-mg" title="新会员注册活动"></uni-section>
        <li-form-item label="赠送积分">
          <view class="inner-input-container">
            <li-input class="inner-input" v-model="form.sendPoints" />分
          </view>
        </li-form-item>

        <!-- 优惠券 -->
        <view
          style="
            justify-content: space-between;
            display: flex;
            margin-top: 10px;
            margin-bottom: 10px;
          "
        >
          <view style="font-weight: bold">赠送优惠券</view>
          <view
            class="form-item-right"
            style="
              display: flex;
              flex: unset;
              justify-content: flex-end;
              color: #f3c45d;
              font-weight: bold;
            "
            @click="addCoupon(1)"
            >新增</view
          >
        </view>
        <view class="spec-container">
          <view class="spec-body">
            <block v-if="form.sendCounpon.length > 0">
              <view>
                <view
                  class="items"
                  style="border-bottom: 1px solid #cacaca; padding: 8px 0"
                >
                  <view class="is-default">券名称</view>
                  <view class="spec-name task-price">券类型</view>
                  <view class="price task-option">券面值</view>
                  <view class="price task-option">数量</view>
                  <view class="btns task-btn">操作</view></view
                >
              </view>
              <view
                v-for="(item, index) in form.sendCounpon"
                :key="item.id"
                class="items"
              >
                <view class="is-default">
                  <text>
                    {{ item.name }}
                  </text>
                </view>
                <view class="spec-name task-price">
                  {{
                    couponTypeEnum.find((it) => it.id == item.typeId).text
                  }}</view
                >
                <view class="price task-option">
                  <text>
                    {{ item.parValue }}
                  </text>
                </view>
                <view class="price task-option">
                  <li-input
                    style="width: 30px; border-bottom: 1px solid #cacaca"
                    v-model="item.number"
                    rule="int"
                  />
                </view>
                <view class="btns task-btn">
                  <text
                    class="btn btn-del"
                    @click="btnDelCouponItemClick(index, 1)"
                    style="margin-left: 8px"
                    >删除</text
                  >
                </view>
              </view>
            </block>
            <block v-else> 暂无优惠券，请点击右上角添加~~ </block>
          </view>
        </view>

        <uni-section class="section-mg" title="会员生日活动" />
        <li-form-item label="赠送积分">
          <view class="inner-input-container">
            <li-input class="inner-input" v-model="form.borthSendPoints" />分
          </view>
        </li-form-item>
        <!-- 优惠券 -->
        <view
          style="
            justify-content: space-between;
            display: flex;
            margin-top: 10px;
            margin-bottom: 10px;
          "
        >
          <view style="font-weight: bold">赠送优惠券</view>
          <view
            class="form-item-right"
            style="
              display: flex;
              flex: unset;
              justify-content: flex-end;
              color: #f3c45d;
              font-weight: bold;
            "
            @click="addCoupon(2)"
            >新增</view
          >
        </view>
        <view class="spec-container">
          <view class="spec-body">
            <block v-if="form.borthSendCounpon.length > 0">
              <view>
                <view
                  class="items"
                  style="border-bottom: 1px solid #cacaca; padding: 8px 0"
                >
                  <view class="is-default">券名称</view>
                  <view class="spec-name task-price">券类型</view>
                  <view class="price task-option">券面值</view>
                  <view class="price task-option">数量</view>
                  <view class="btns task-btn">操作</view></view
                >
              </view>
              <view
                v-for="(item, index) in form.borthSendCounpon"
                :key="item.id"
                class="items"
              >
                <view class="is-default">
                  <text>
                    {{ item.name }}
                  </text>
                </view>
                <view class="spec-name task-price">
                  {{
                    couponTypeEnum.find((it) => it.id == item.typeId).text
                  }}</view
                >
                <view class="price task-option">
                  <text>
                    {{ item.parValue }}
                  </text>
                </view>
                <view class="price task-option">
                  <li-input
                    style="width: 30px; border-bottom: 1px solid #cacaca"
                    v-model="item.number"
                    rule="int"
                  />
                </view>
                <view class="btns task-btn">
                  <text
                    class="btn btn-del"
                    @click="btnDelCouponItemClick(index, 2)"
                    style="margin-left: 8px"
                    >删除</text
                  >
                </view>
              </view>
            </block>
            <block v-else> 暂无优惠券，请点击右上角添加~~ </block>
          </view>
        </view>
        <li-form-item label="当日双倍积分" class="fs12" :border="false">
          <li-switch v-model="form.borthDoublePoint" />
        </li-form-item>
        <uni-section class="section-mg" title="会员日活动"></uni-section>
        <li-form-item label="会员日方式">
          <li-picker
            v-model="form.memberDayType"
            :range-list="[
              {
                id: 1,
                text: '按日期',
              },
              {
                id: 2,
                text: '按周',
              },
            ]"
        /></li-form-item>
        <li-form-item v-show="form.memberDayType == 2">
          <li-checkbox
            :range-list="weekEnumable"
            v-model="form.memberDayMonth"
          />
        </li-form-item>
        <li-form-item v-show="form.memberDayType == 1">
          <li-checkbox :range-list="dayEnum" v-model="form.memberDayMonth" />
        </li-form-item>
        <li-form-item label="积分活动">
          <view class="inner-input-container">
            当日消费
            <li-input
              class="inner-input"
              v-model="form.memberDayPoint"
              rule="float"
            />倍积分
          </view>
        </li-form-item>
        <li-form-item label="活动状态" :border="false">
          <li-switch v-model="form.memberDayStatus" />
        </li-form-item>
      </li-form>
    </view>
    <li-bottom-btns
      :mode="mode"
      @btnDelClick="btnDelClick"
      @btnEditOrSaveSubmitClick="btnEditOrSaveSubmitClick"
    />

    <!-- popup -->
    <u-popup :show="show" @close="close" @open="open" :closeable="true">
      <view
        class="layout"
        style="
          height: 90vh;
          width: 100vw;
          background-color: #f7f8fa;
          font-size: 12px;
          display: flex;
        "
      >
        <view
          class="layout-left"
          style="height: 100%; width: 30vw; overflow-y: scroll"
        >
          <view
            style="
              margin: 15rpx;
              background-color: #fff;
              border-radius: 10px;
              padding: 8px 12px;
            "
            :style="{
              color: popLeftTabsIdx == index ? '#f3c45d' : '#000',
            }"
            @click="popLeftTabsClick(index)"
            v-for="(item, index) in couponTypeEnum"
            :key="item.id"
          >
            {{ item.text }}
          </view>
        </view>
        <view
          class="layout-right"
          style="
            height: 100%;
            width: 70vw;
            overflow-y: scroll;
            padding-top: 40px;
            padding-right: 5px;
          "
        >
          <block v-if="popPageList != null && popPageList.length > 0">
            <view
              v-for="(item, index) in popPageList"
              :key="item.id"
              style="display: flex; align-items: center; margin-bottom: 10px"
            >
              <view style="flex: 1; font-weight: 900; padding-left: 12px">
                {{ item.name }}
              </view>
              <button
                size="mini"
                @click="btnPopItemSelectClick(item)"
                class="btn-yellow"
                style="border-radius: 8px; color: #fff"
                :style="{
                  'background-color': form[
                    popType == 1 ? 'sendCounpon' : 'borthSendCounpon'
                  ].some((itm) => itm.id == item.id)
                    ? '#f56c6c'
                    : '#24c322',
                }"
              >
                {{
                  form[popType == 1 ? "sendCounpon" : "borthSendCounpon"].some(
                    (itm) => itm.id == item.id
                  )
                    ? "取消"
                    : "选择"
                }}
              </button>
            </view>
          </block>
          <li-empty v-else />
        </view>
      </view>
    </u-popup>
  </view>
</template>
<script>
import liFormMixin from "../../../mixins/liFormMixin";
import { liChecker } from "@/common/graceChecker";
import {
  GetUserPointRuleList,
  EditUserPointRule,
  GetFoodCouponList,
} from "../../../common/api.js";
import {
  uNavigateBack,
  uShowLoading,
  uHideLoading,
  umodal,
  utoast,
  uSwitchTab,
} from "../../../utils/uniUtils";
import { transferTypeEnum, transfer } from "../../../common/dataTransfer.js";
import {
  checkerType,
  modeEnum,
  booleanEnum,
  weekEnumable,
  dayEnum,
  couponTypeEnum,
} from "../../../constants/normalConstants.js";
import { toastIconEnum } from "../../../constants/uiConstants";
import { batchJsonParse, batchJsonStringify } from "../../../utils/liJsonUtils";
export default {
  mixins: [liFormMixin],
  async onLoad(options) {
    // this.loadEvent(options, this);
  },
  async mounted() {
    try {
      uShowLoading();
      await this.getData();
      this.isLoaded = true;
      uHideLoading();
    } catch (error) {
      console.log("error", error);
      utoast("页面初始化失败！", "error");
      setTimeout(() => {
        uSwitchTab("/pages/tabBar/staging");
      }, 800);
    }
  },
  data() {
    return {
      /* 枚举 */
      couponTypeEnum,
      weekEnumable,
      dayEnum,
      modeEnum,
      booleanEnum,
      subject: "积分规则", // 主题
      rootRoute: "workbench",
      routeName: "integralRules",
      mode: "add", // 模式
      isLoaded: false,
      id: null,
      /* 表单 */
      form: null,
      /* 弹窗 */
      show: false,

      // 数据转换器
      transferRules: [
        /*     {
          name: "depositMoney",
          type: transferTypeEnum.float,
        }, */
      ],
      //表单校验规则
      rules: [
        /*         {
          name: "startTime",
          checkType: checkerType.endNotNull,
          errorMsg: "开始时间不能为空~~",
        },
        {
          name: "endTime",
          checkType: checkerType.endNotNull,
          errorMsg: "结束时间不能为空~~",
        }, */
      ],
      lock: false, // 节流锁

      /* 额外数据 */
      UserCategoryList: [],
      FoodCouponList: [],
      popLeftTabsIdx: 0,
      popPageList: [],
      popType: 1,
      /* 额外校验规则 */
      /* 额外转换器 */
      jsonProp: [
        "sendCounpon",
        "borthSendCounpon",
        "memberDayWeek",
        "memberDayMonth",
      ],
    };
  },

  methods: {
   
    onBlurEvent(e) {
      this.formBlur(e, this);
    },

    
    async getData() {
      this.form = batchJsonParse(
        (await GetUserPointRuleList(this.id)).data.list[0],
        this.jsonProp
      );
    },
    
    async getOtherData() {
      // ..
    },
   
    async insertData() {},
    
    async delData() {},
    
    async editData() {
      return await EditUserPointRule(this.form);
    },

    
    async btnDelClick() {},
    
    async btnEditOrSaveSubmitClick() {
      //  节流锁
      if (this.lock) {
        return;
      }

      if (!(await umodal("确认要提交吗？"))) {
        return;
      }

      // 数据转换
      this.form = transfer(this.form, this.transferRules);

      // 表单校验
      let isOk = liChecker.check(this.form, this.rules);
      if (!isOk) {
        await utoast(liChecker.error, toastIconEnum.none);
        return;
      }

      //  提交表单
      const res = await this.editData(
        batchJsonStringify(this.form, this.jsonProp)
      );

      if (res?.code == 0) {
        await utoast("操作成功");
        setTimeout(() => {
          uNavigateBack();
        }, 500);
      } else {
        setTimeout(() => {
          this.lock = false;
        }, 2000);
      }
    },

    /* 额外方法放下面，上面是主干方法 */
    getPopPageList: async function (params) {
      this.popPageList = (
        await GetFoodCouponList({
          pageNum: 1,
          pageSize: 9999,
          typeId: this.couponTypeEnum[this.popLeftTabsIdx]["id"],
        })
      ).data.list;
    },
    btnPopItemSelectClick: async function (params) {
      const res = this.form[
        this.popType == 1 ? "sendCounpon" : "borthSendCounpon"
      ].some((itm) => itm.id == params.id);
      if (res) {
        const idx = this.form[
          this.popType == 1 ? "sendCounpon" : "borthSendCounpon"
        ].findIndex((itm) => itm.id == params.id);
        this.form[
          this.popType == 1 ? "sendCounpon" : "borthSendCounpon"
        ].splice(idx, 1);
      } else {
        this.form[this.popType == 1 ? "sendCounpon" : "borthSendCounpon"].push({
          ...params,
          number: 1,
        });
      }
    },
    close: function () {
      this.show = false;
    },
    open: function () {
      this.popLeftTabsIdx = 0;
      this.show = !false;
      this.getPopPageList();
    },
    popLeftTabsClick: function (i) {
      this.popLeftTabsIdx = i;
      this.getPopPageList();
    },
    btnDelCouponItemClick: function (idx, type) {
      this.form[type == 1 ? "sendCounpon" : "borthSendCounpon"] = this.form[
        type == 1 ? "sendCounpon" : "borthSendCounpon"
      ].filter((_item, index) => index != idx);
    },
    addCoupon(type) {
      this.popType = type;
      this.open();
    },
    //方法放上面
  },
};
</script>
<style lang="scss" scoped>
@import "~@/static/styles/commonStyle.scss";

.inner-input-container {
  display: flex;
  align-items: center;

  .inner-input {
   // border-bottom: 1px solid #cacaca;
    width: 60px;
    padding-left: 8px;
    margin-right: 3px;
  }
}

.spec-container {
  background-color: #fff;
  border-radius: 10px;
  margin: 10px 0;
  padding: 8px 4px;

  .spec-header {
    padding: 10px;
    border-bottom: 1px solid #ededed;
    display: flex;
    justify-content: space-between;
  }

  .spec-body {
    padding: 15px 10px;

    .items {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 12px;
      border-bottom: 1px solid #cacaca;
      padding: 8px 0;
      &:last-child {
        border-bottom: none;
      }

      .is-default {
        width: 80px;
        display: flex;
        justify-content: center;
        color: #000;
        background-color: #fff;
        .is-default-active {
          color: #fff;
          background-color: #fdc31d;
        }
      }

      .spec-name {
        flex: 1;
        display: flex;
        justify-content: center;
        &.task-price {
          width: 80px;
        }
      }

      .price {
        width: 80px;
        display: flex;
        justify-content: center;
        &.task-option {
          width: 60px;
        }
      }

      .btns {
        width: 90px;
        display: flex;
        justify-content: center;
        &.task-btn {
          width: 70px;
          font-size: 12px;
        }
      }

      .btn {
        border: 1px solid #ededed;
        padding: 12rpx 12rpx;
        border-radius: 5rpx;
        &.btn-del {
          background-color: #f56c6c;
          color: #fff;
        }
      }
    }
  }
}
</style>
